package com.example.java_chatroom.api;

import com.example.java_chatroom.component.PasswordTools;
import com.example.java_chatroom.model.User;
import com.example.java_chatroom.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.example.java_chatroom.component.PasswordTools.decrypt;
import static com.example.java_chatroom.component.PasswordTools.encrypt;


@RestController
public class UserAPI {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest req) {
        // 1. 去数据库中查, 能否找到对应的 User 对象
        //    如果能找到, 看看密码匹不匹配
        User user = userMapper.selectByName(username);

        if (user == null || !decrypt(password, user.getPassword())) {
            // 登录失败! 返回一个空的对象
            System.out.println("登录失败, 用户名或密码错误!" + user);
            return new User();
        }

        // 2. 都匹配, 创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        // 返回之前, 把 password 干掉, 避免返回不必要的信息
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    public Object register(String username, String password) {
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(encrypt(password));
            int ret = userMapper.insert(user);
            System.out.println("注册 ret: " + ret);
            user.setPassword("");
        } catch (DuplicateKeyException e) {
            // 如果 insert 方法抛出上述异常, 说明名字重复了, 注册失败
            user = new User();
            System.out.println("注册失败 username = " + username);
        }
        return user;
    }

    @GetMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest req, @SessionAttribute("user") User user) {
//        // 1. 从请求中获取到会话
//        HttpSession session = req.getSession(false);
//        if (session == null) {
//            System.out.println("[getUserInfo] session == null!");
//            return new User();
//        }
//        // 2. 从会话中获取到之前保存的对象
//        User user = (User) session.getAttribute("user");
//        if (user == null) {
//            System.out.println("[getUserInfo] 当前获取不到 user 对象!");
//            return new User();
//        }
        user.setPassword("");
        return user;
    }
}
